package org.feifei.basic.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.feifei.basic.util.CommonResult;
import org.feifei.basic.util.FastDfsUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;

/**
 * @author forever
 * @Description: FastDFS接口 封装图片的上传与删除
 *               @RequestPart注解 专门用于接收MultiPartFile对象
 * @date 2021/12/06 15:45
 *
 */
@RestController
@Api(tags = "FastDFS的使用接口")
@RequestMapping("fastDfs")
public class FastDFSController {

    /**
     * 通过FasfDFS 上传文件
     * @param file
     * @return
     */
    @PostMapping
    public CommonResult<System> upLoad(@RequestPart(required = true,name = "file") MultipartFile file) {
        if (!file.isEmpty()) {
            String name = file.getOriginalFilename().substring(file.getOriginalFilename().indexOf(".") + 1);
            try {
                String path = FastDfsUtil.upload(file.getBytes(), name);
                return CommonResult.ok(path);
            } catch (Exception e) {
                e.printStackTrace();
                return CommonResult.failure(e.getMessage());
            }
        }
        return CommonResult.failure("文件不能为空");
    }

    /**
     * 根绝path 来删除文件
     * @param path
     * @return
     */
    @ApiOperation("删除图片")
    @DeleteMapping
    public CommonResult delete(@RequestParam(required = true,value = "path")String path) {
        try {
            String tmpName = path.substring(1);
            String filePath = tmpName.substring(tmpName.indexOf("/") + 1);
            String groupName = tmpName.substring(0, tmpName.indexOf("/"));
            FastDfsUtil.delete(groupName,filePath);
            return CommonResult.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failure(e.getMessage());
        }
    }
}
